package com.young.jdbc;

import com.young.jdbc.myjdbc.JdbcUtils;
import org.junit.Test;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.SQLException;

/**
 * @Author: young
 * @Date: 2021-12-03 14:51
 * @Description: java的批处理
 */
public class Batch {
	// 不使用批处理
	@Test
	public void noBatch() throws SQLException {
		Connection connection = JdbcUtils.getConnection();
		String sql = "insert into admin values(?,?)";
		PreparedStatement preparedStatement = connection.prepareStatement(sql);

		long start = System.currentTimeMillis();
		for (int i=0;i<2000;i++){
			preparedStatement.setString(1,"hello"+i);
			preparedStatement.setString(2,"666");
			preparedStatement.executeUpdate();
		}
		long end = System.currentTimeMillis();
		System.out.println("不使用批处理：耗时为"+(end-start));
		JdbcUtils.close(null,preparedStatement,connection);
	}

	// 使用批处理
	@Test
	public void useBatch() throws SQLException {
		Connection connection = JdbcUtils.getConnection();
		String sql = "insert into admin values(?,?)";
		PreparedStatement preparedStatement = connection.prepareStatement(sql);

		long start = System.currentTimeMillis();
		for (int i=0;i<2000;i++){
			preparedStatement.setString(1,"hello"+i);
			preparedStatement.setString(2,"666");
			// 将SQL语句加入到批处理包中
			preparedStatement.addBatch();
			// 当有1000条记录时，再批量执行
			if ((i+1) % 1000 == 0){
				preparedStatement.executeBatch();
				// 清空一下
				preparedStatement.clearBatch();
			}
		}
		long end = System.currentTimeMillis();
		System.out.println("不使用批处理：耗时为"+(end-start));
		JdbcUtils.close(null,preparedStatement,connection);
	}
}
